package com.yx.shop.config;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yx.shop.tools.R;
import com.yx.shop.tools.S;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
//日志系统  可以通用修改配置文件来存储到文件中（本地硬盘）
@Slf4j
public class GlobalRestExceptionConfig {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handleException(SQLIntegrityConstraintViolationException e) {
        log.error("数据已存在 : {}", e.getMessage());
        return R.failure("数据已存在");
    }

    /**
     * 节点添加的限流以后的处理功能
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BlockException.class)
    public R<String> returnString(BlockException ex) {
        log.warn("限流 : {}", ex.getMessage());
        return R.build(S.SENTINEL_BLOCK, S.SENTINEL_BLOCK.getMsg());
    }

    @ExceptionHandler(RuntimeException.class)
    public R<String> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常 : {}", e.getMessage());
        return R.failure("运行时异常");
    }

}
